package com.xiaoma.verbal.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.tpo.utils.PagingOrder;
import com.xiaoma.verbal.dao.QuQuestionDao;
import com.xiaoma.verbal.dao.QuTagDao;
import com.xiaoma.verbal.dao.TagTableDao;
import com.xiaoma.verbal.domain.QuQuestion;
import com.xiaoma.verbal.domain.QuTag;
import com.xiaoma.verbal.domain.TagTable;
import com.xiaoma.verbal.dto.QuClassicVo;
import com.xiaoma.verbal.dto.QuestionVo;
import com.xiaoma.verbal.utils.ExcelUtil;

@Service
public class QuestionService extends BaseQuestionService {

	@Autowired
	private QuQuestionDao quQuestionDao;

	@Autowired
	private QuTagDao quTagDao;

	@Autowired
	private TagTableDao tagTableDao;

	public Pager list(Integer id, Integer questionType, String qnum, String tagText, String content, Integer page, Integer pageSize) {
		if (page == null || page==0) {
			page = 1;
			pageSize = 50;
		}
		Pager pager = quQuestionDao.queryPageList(id, questionType, qnum, tagText, content, (page - 1) * pageSize, pageSize);
		List<QuestionVo> list = pager.getList();
		for (QuestionVo vo : list) {
			vo.setTags(this.quTagDao.findTagByQuestionId(vo.getId()));
		}

		return pager;
	}

	public int importData(int version, InputStream fis) // TODO Auto-generated
														// method stub
			throws Exception {
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = null;
		try {
			// excel数据
			if (version == 2003) {
				list = ExcelUtil.parseExcel_2003(fis);
			} else {
				list = ExcelUtil.parseExcel_2007(fis);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 2;
		}
		try {
			// 保存数据
			for (Map<String, Object> m : list) {
				saveDate(m, 0);
			}

		} catch (Exception e) {
			throw e;
		} finally {
			// 刷新缓存
			this.afterChanger();
		}

		return 1;
	}

	private void saveDate(Map<String, Object> map, int type) throws Exception {
		final String qNum = (String) map.get("question_num");
		final String idstr = (String) map.get("qid");// 导入时此项不存在
		final Integer bankType = (Integer) map.get("bankType");

		if (qNum != null && qNum.length() > 0) {

			// 保存或更新题
			// 导入时通过题号判断是否已存在，存在的话则覆盖
			QuQuestion oldqb = quQuestionDao.findByQnum(qNum);
			System.out.println(qNum);
			if (oldqb != null) {
				if (type == 0) {
					dealKyQb(oldqb, map, type);
				} 
			} else {
				QuQuestion qb = new QuQuestion();
				// id不为空则更新
				if (idstr != null && idstr.length() > 0) {
					qb.setId(Integer.parseInt(idstr));
				}
				if (type == 0) {
					dealKyQb(qb, map, type);
				} 
			}
		}

	}

	/**
	 * 处理题库--口语
	 * 
	 * @param qb
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	private void dealKyQb(QuQuestion qb, Map<String, Object> rowmap, int type) throws Exception {

		final String idstr = (String) rowmap.get("qid");// 导入时此项不存在,单个修改时才不为空
		final String qNum = (String) rowmap.get("question_num");
		final String content = (String) rowmap.get("content");
		final String tags = (String) rowmap.get("tags");
		final String translation = (String) rowmap.get("translation");
		final String keyword_audiourls = (String) rowmap.get("keyword_audiourl");
		final String review = (String) rowmap.get("review");// 老师点评

		if (!qNum.startsWith("S_")) {
			// 错误，口语是以S_开头
			throw new Exception("内容有误，应该上传口语");
		}

		qb.setQuestionNum(qNum);
		if ((content != null && content.length() > 0) || idstr != null) {
			qb.setContent(content);
		}
		if ((translation != null && translation.length() > 0) || idstr != null) {
			qb.setTranslation(translation);
		}
		qb.setQuestionType(type);

		if (qb.getId() != null && qb.getId() > 0) {
			qb.setUpdateTime(new Date());
		} else {
			Date date = new Date();
			qb.setCreateTime(date);
			qb.setUpdateTime(date);
		}
		if (qb.getId() != null) {
			quQuestionDao.update(qb);
		} else {
			qb.setId(quQuestionDao.insert(qb));
		}

		// 题库标签
		dealTags(qb, tags, idstr, type);
	}

	
	/**
	 * 处理标签
	 * 
	 * @param tags
	 * @param arryTags
	 * @throws Exception
	 */
	public void dealTags(QuQuestion qb, String tags, String idstr, int type) throws Exception {
		QuTag bean = new QuTag();
		bean.setQuestionId(qb.getId());
		quTagDao.deleteByQId(qb.getId());
		if (tags != null && tags.length() > 0) {
			for (String str : tags.split("/")) {
				if (StringUtils.hasText(str) && StringUtils.hasLength(str) && !"无".equals(str)) {

					if (str.length() > 3) {
						System.out.println(str.length());
						str = str.trim();
						System.out.println(str.length());
					}
					str = str.replace(" ", "");
					str = str.trim();
					TagTable tag = tagTableDao.findByTypeAndText(0, str);
					// 判断tag是否添加过
					if (tag == null) {
						tag = new TagTable();
						tag.setTagType(type);
						tag.setTagText(str);
						tag.setId(tagTableDao.insert(tag));
					}
					QuTag qtag = new QuTag();
					qtag.setQuestionId(qb.getId());
					qtag.setTagId(tag.getId());
					quTagDao.insert(qtag);
				}
			}
		}
	}

	public int update(QuQuestion bean) {
		// TODO Auto-generated method stub
		return this.quQuestionDao.update(bean);
	}

	public void update(Integer qid, String questionType, String questionNum, String content, String qtags, String translation) throws Exception {
		// TODO Auto-generated method stub
		QuQuestion qb = this.quQuestionDao.getById(qid);
		if (qb != null) {
			qb.setQuestionType(questionType.equals("口语") ? 0 : 1);
			qb.setQuestionNum(questionNum);
			qb.setContent(content);
			qb.setTranslation(translation);
			qb.setUpdateTime(new Date());
			this.quQuestionDao.update(qb);
			this.dealTags(qb, qtags, null, 0);
			// 刷新缓存
			this.afterChanger();
		} else {
			return;
		}

	}

	public void save(Integer qid, String questionType, String questionNum, String content, String qtags, String translation) throws Exception {
		// TODO Auto-generated method stub
		QuQuestion qb = new QuQuestion();
		qb.setQuestionType(questionType.equals("口语") ? 0 : 1);
		qb.setQuestionNum(questionNum);
		qb.setContent(content);
		qb.setTranslation(translation);
		qb.setTimeLimit(45);
		qb.setCreateTime(new Date());
		qb.setUpdateTime(qb.getCreateTime());
		qb.setId(this.quQuestionDao.insert(qb));
		// 处理标签
		this.dealTags(qb, qtags, null, 0);
		// 刷新缓存
		this.afterChanger();
	}

	public int checkQnumIsExist(String questionNum) {
		// TODO Auto-generated method stub
		QuQuestion bean = new QuQuestion();
		bean.setQuestionNum(questionNum);
		List<QuQuestion> list = this.quQuestionDao.findByColumns(bean);
		if (!CollectionUtils.isEmpty(list)) {
			return 1;
		}
		return 0;

	}
}
